#!/usr/bin/env bash

requirements_openbsd_lib_installed()
{
  pkg_info | __rvm_grep "^$1" >/dev/null 2>&1 || return $?
}

requirements_openbsd_lib_available()
{
  pkg_info -Q "${1%%-[[:digit:]]}" | __rvm_grep "^$1" >/dev/null 2>&1 || return $?
}

requirements_openbsd_libs_install()
{
  __rvm_try_sudo pkg_add -z "$@" || return $?
}

requirements_openbsd_install_node()
{
  # plain make is required for sudo
  __rvm_try_sudo make -C /usr/ports/www/node install clean || return $?
}

requirements_openbsd_update_system()
{
  [[ -d /usr/ports ]] ||
  {
    \typeset __url __target __result=0
    __url="http://ftp.openbsd.org/pub/OpenBSD/${_system_version}/ports.tar.gz"
    __target="$( TMPDIR="${rvm_tmp_path}" mktemp ${TMPDIR:-/tmp}/tmp.XXXXXXXXXXXXXXXXXX )"
    __rvm_curl "${__url}" -o "${__target}"        &&
    __rvm_try_sudo tar -C /usr -zxf "${__target}" ||
    __result=$?
    rm -f "${__target}"
    return ${__result}
  }
  true
}

requirements_openbsd_define()
{
  case "$1" in
    (rvm)
      requirements_check bash curl
      ;;

    (jruby*)
      requirements_check make jdk

      if
        is_head_or_disable_binary "$1"
      then
        requirements_check git
        case $( jruby_installation_method  "$1" ) in
          ant) requirements_check apache-ant ;;
          mvn) requirements_check maven      ;;
        esac
      fi
      ;;

    (ir*)
      requirements_check mono
      ;;

    (opal)
      requirements_check_custom node
      ;;

    (ruby-1.9.3*|ruby-2.0.0*)
      rvm_error "Beware there is a compilation bug in $1 on OpenBSD, it's fixed in ruby-2.1.0
for more details see https://bugs.ruby-lang.org/issues/7959"
      return 103
      ;;

    (*-head)
      # OpenSSL is installed by default http://www.openbsd.org/crypto.html
      requirements_check gcc-4 automake-1 libtool bison readline-6 libyaml-0 git
      requirements_check_fallback autoconf-2.69p0 autoconf-2.68 autoconf-2.67
      __rvm_update_configure_opt_dir "$1" "/usr/local"
      ;;

    (*)
      # OpenSSL is installed by default http://www.openbsd.org/crypto.html
      requirements_check gcc-4 autoconf-2 automake-1 libtool bison readline-6 libyaml-0
      __rvm_update_configure_opt_dir "$1" "/usr/local"
      ;;
  esac
}

requirements_openbsd_before()
{
  [[ -n "${PKG_PATH:-}" ]] ||
  {
    export PKG_PATH=http://ftp.openbsd.org/pub/OpenBSD/${_system_version}/packages/$(arch -s)/
    rvm_warn "WARNING: \$PKG_PATH was not set, using fallback '$PKG_PATH',
see http://www.openbsd.org/ftp.html for list of available mirrors."
  }
}
